using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using Exiled.API.Enums;
using Exiled.API.Features;
using Exiled.API.Features.Pools;
using HarmonyLib;
using Respawning.NamingRules;
using RgCore.CustomSide;

namespace CustomCharacter.Patches
{
    [HarmonyPatch(typeof(NineTailedFoxNamingRule), nameof(NineTailedFoxNamingRule.PlayEntranceAnnouncement))]
    internal static class PlayEntranceAnnouncementPath
    {
        [HarmonyTranspiler]
        private static IEnumerable<CodeInstruction> PlayEntranceAnnouncementTranspiler(
            IEnumerable<CodeInstruction> instructions)
        {
            List<CodeInstruction> codeInstructions = ListPool<CodeInstruction>.Pool.Get(instructions);
            int index = codeInstructions.FindIndex(x => x.opcode == OpCodes.Call);
            while (true)
            {
                if (codeInstructions[index].opcode == OpCodes.Stloc_1)
                {
                    break;
                }

                codeInstructions.RemoveAt(index);
            }

            codeInstructions.InsertRange(index, new[]
            {
                CodeInstruction.Call(typeof(PlayEntranceAnnouncementPath), nameof(GetScpCount)),
            });
            foreach (CodeInstruction code in codeInstructions)
            {
                yield return code;
            }

            ListPool<CodeInstruction>.Pool.Return(codeInstructions);
        }

        private static int GetScpCount()
        {
            return Player.List.Count(player => player.GetSide() == Side.Scp);
        }
    }
}